'use client';

// 云存储文件浏览弹框组件（简化版）
// REF: API-CLOUD-FILES-010

import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Folder,
  File,
  ArrowLeft,
  ArrowRight,
  Home,
  RefreshCw,
  ChevronRight,
  ArrowUp,
  FolderPlus,
} from 'lucide-react';
import { CloudStorageAccount } from '@/services/cloudAccountApi';
import { cloudFilesApi, CloudFile } from '@/services/cloudFilesApi';
import { formatBytes, formatDate } from '@/lib/utils';

interface CloudFilesDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  account: CloudStorageAccount | null;
}

export function CloudFilesDialog({ open, onOpenChange, account }: CloudFilesDialogProps) {
  const [files, setFiles] = useState<CloudFile[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPath, setCurrentPath] = useState('/');
  const [pathHistory, setPathHistory] = useState<string[]>(['/']);
  const [forwardHistory, setForwardHistory] = useState<string[]>([]);
  const [breadcrumbPath, setBreadcrumbPath] = useState<{id: string, name: string}[]>([{id: '', name: '根目录'}]);
  const [showCreateFolderDialog, setShowCreateFolderDialog] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');

  // 加载文件列表
  const loadFiles = async (folderId: string = '') => {
    if (!account) return;
    
    try {
      setLoading(true);
      
      const response = await cloudFilesApi.getFiles({
        accountId: account.id,
        folderId: folderId,
        pageNum: 1,
        pageSize: 100,
        autoLogin: true
      });
      
      if (response.success && response.data) {
        setFiles(response.data.files || []);
      } else {
        setFiles([]);
      }
    } catch (error) {
      console.error('Failed to load files:', error);
      setFiles([]);
    } finally {
      setLoading(false);
    }
  };



  // 初始加载
  useEffect(() => {
    if (open && account) {
      setCurrentPath('');
      setPathHistory(['']);
      setForwardHistory([]);
      setBreadcrumbPath([{id: '', name: '根目录'}]);
      loadFiles('');
    }
  }, [open, account]);

  // 导航到指定文件夹
  const navigateToFolder = (folderId: string, folderName?: string) => {
    // 清空前进历史
    setForwardHistory([]);
    
    setCurrentPath(folderId);
    setPathHistory(prev => [...prev, folderId]);
    
    // 更新面包屑路径
    if (folderName) {
      setBreadcrumbPath(prev => [...prev, {id: folderId, name: folderName}]);
    }
    
    loadFiles(folderId);
  };

  // 返回上级目录
  const goBack = () => {
    if (pathHistory.length <= 1) return;
    
    const currentFolderId = pathHistory[pathHistory.length - 1];
    setForwardHistory(prev => [currentFolderId, ...prev]);
    
    const newHistory = pathHistory.slice(0, -1);
    const parentFolderId = newHistory[newHistory.length - 1];
    setPathHistory(newHistory);
    setCurrentPath(parentFolderId);
    
    // 更新面包屑路径
    setBreadcrumbPath(prev => prev.slice(0, -1));
    
    loadFiles(parentFolderId);
  };

  // 前进
  const goForward = () => {
    if (forwardHistory.length === 0) return;
    
    const nextFolderId = forwardHistory[0];
    setForwardHistory(prev => prev.slice(1));
    setPathHistory(prev => [...prev, nextFolderId]);
    setCurrentPath(nextFolderId);
    
    // 这里需要根据文件夹ID获取名称，暂时使用ID
    setBreadcrumbPath(prev => [...prev, {id: nextFolderId, name: nextFolderId || '根目录'}]);
    
    loadFiles(nextFolderId);
  };

  // 返回根目录
  const goHome = () => {
    if (currentPath === '') return;
    
    setForwardHistory([]);
    setCurrentPath('');
    setPathHistory(['']);
    setBreadcrumbPath([{id: '', name: '根目录'}]);
    loadFiles('');
  };

  // 跳转到面包屑中的特定路径
  const navigateToBreadcrumb = (index: number) => {
    const targetPath = breadcrumbPath[index];
    if (!targetPath) return;
    
    // 清空前进历史
    setForwardHistory([]);
    
    setCurrentPath(targetPath.id);
    setPathHistory(prev => prev.slice(0, index + 1));
    setBreadcrumbPath(prev => prev.slice(0, index + 1));
    
    loadFiles(targetPath.id);
  };

  // 创建文件夹
  const createFolder = async () => {
    if (!newFolderName.trim()) {
      alert('请输入文件夹名称');
      return;
    }

    try {
      setLoading(true);
      const response = await fetch('/api/cloud-files/create-folder', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          accountId: account?.id,
          parentFolderId: currentPath,
          folderName: newFolderName.trim(),
        }),
      });

      if (response.ok) {
        setShowCreateFolderDialog(false);
        setNewFolderName('');
        // 刷新文件列表
        loadFiles(currentPath);
      } else {
        const errorData = await response.json();
        alert(`创建文件夹失败: ${errorData.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('创建文件夹失败:', error);
      alert('创建文件夹失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 刷新当前目录
  const refresh = () => {
    loadFiles(currentPath);
  };



  if (!account) return null;

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-[98vw] w-[1600px] max-h-[95vh] h-[800px] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Folder className="h-5 w-5" />
              文件浏览 - {account.cloudAccount}
            </DialogTitle>
            <DialogDescription>
              浏览 {account.cloudProvider === 'tianyi' ? '天翼云盘' : account.cloudProvider} 中的文件和文件夹
            </DialogDescription>
          </DialogHeader>
          
          {/* 导航栏 */}
          <div className="flex items-center gap-2 p-4 border-b">
            <Button
              variant="outline"
              size="sm"
              onClick={goBack}
              disabled={pathHistory.length <= 1}
              title="后退"
            >
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={goForward}
              disabled={forwardHistory.length === 0}
              title="前进"
            >
              <ArrowRight className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={goBack}
              disabled={pathHistory.length <= 1}
              title="返回上级目录"
            >
              <ArrowUp className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={refresh}
              title="刷新"
            >
              <RefreshCw className="h-4 w-4" />
            </Button>
          </div>
          
          {/* 面包屑导航 */}
          <div className="flex items-center gap-1 px-4 py-2 bg-gray-50 overflow-x-auto">
            <span className="text-sm text-gray-600 mr-2">位置:</span>
            {breadcrumbPath.map((path, index) => (
              <div key={index} className="flex items-center gap-1">
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-6 px-2 text-sm hover:bg-gray-200 flex items-center gap-1"
                  onClick={() => navigateToBreadcrumb(index)}
                >
                  {index === 0 ? (
                    <Home className="h-3 w-3" />
                  ) : (
                    path.name
                  )}
                </Button>
                {index < breadcrumbPath.length - 1 && (
                  <ChevronRight className="h-3 w-3 text-gray-400" />
                )}
              </div>
            ))}
            <Button
              variant="ghost"
              size="sm"
              className="h-6 px-2 ml-2 text-sm hover:bg-gray-200 flex items-center gap-1"
              onClick={() => setShowCreateFolderDialog(true)}
              title="新建文件夹"
            >
              <FolderPlus className="h-3 w-3" />
            </Button>
          </div>
          
          {/* 文件列表 */}
          <div className="flex-1 overflow-auto">
            {loading ? (
              <div className="flex items-center justify-center h-32">
                <RefreshCw className="h-6 w-6 animate-spin" />
                <span className="ml-2">加载中...</span>
              </div>
            ) : files.length === 0 ? (
              <div className="flex items-center justify-center h-32">
                <span className="text-gray-500">此文件夹为空</span>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>名称</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead>大小</TableHead>
                    <TableHead>修改时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {files.map((file) => (
                    <TableRow key={file.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {file.isFolder ? (
                            <Folder className="h-4 w-4 text-blue-500" />
                          ) : (
                            <File className="h-4 w-4 text-gray-500" />
                          )}
                          <span
                            className={file.isFolder ? "cursor-pointer hover:text-blue-600" : ""}
                            onClick={() => {
                              if (file.isFolder) {
                                navigateToFolder(file.id, file.name);
                              }
                            }}
                          >
                            {file.name}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={file.isFolder ? "secondary" : "outline"}>
                          {file.isFolder ? "文件夹" : "文件"}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {file.isFolder ? "-" : formatBytes(file.size || 0)}
                      </TableCell>
                      <TableCell>
                        {formatDate(file.modifyTime)}
                      </TableCell>
                    </TableRow>
                  ))}
                  {files.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={4} className="text-center py-8 text-gray-500">
                        此文件夹为空
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            )}
          </div>
        </DialogContent>
      </Dialog>
      
      {/* 新建文件夹对话框 */}
      <AlertDialog open={showCreateFolderDialog} onOpenChange={setShowCreateFolderDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>新建文件夹</AlertDialogTitle>
            <AlertDialogDescription>
              在当前目录下创建一个新的文件夹
            </AlertDialogDescription>
          </AlertDialogHeader>
          <div className="py-4">
            <Label htmlFor="folderName">文件夹名称</Label>
            <Input
              id="folderName"
              value={newFolderName}
              onChange={(e) => setNewFolderName(e.target.value)}
              placeholder="请输入文件夹名称"
              className="mt-2"
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  createFolder();
                }
              }}
            />
          </div>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => {
              setShowCreateFolderDialog(false);
              setNewFolderName('');
            }}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction onClick={createFolder} disabled={!newFolderName.trim()}>
              创建
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}